package cn.yearndr.zfsy.zfsy.service;

import cn.yearndr.zfsy.zfsy.beans.CURDCase;
import cn.yearndr.zfsy.zfsy.mapper.CURDTestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@Service
public class CURDTestService {

    @Autowired
    CURDTestRepository curdTestRepository;

    public CURDCase addCase(){
        CURDCase curdCase = new CURDCase();
        curdCase.setCol("default");
        return curdTestRepository.save(curdCase);
    }

    /**
     * 通过ID查询
     * @param id 需要查找的列的ID
     * @return CURDCase 返回找到的对象实例,未找到对象则返回一个空id实例
     */
    public CURDCase findByID(Integer id){
        Optional<CURDCase> curdCaseOptional =  curdTestRepository.findById(id);
        if (curdCaseOptional.isPresent())return curdCaseOptional.get();
        else{
            CURDCase curdCase = new CURDCase();
            curdCase.setCol("NoFindCase");
            return curdCase;
        }
    }

    /**
     * 更新数据，查询要更新的实例对象，有则更新
     * @param curdCase 实例对象
     * @return CURDCase 更新后的对象,未找到更新对象则返回一个空id对象
     */
    public CURDCase updateByID(CURDCase curdCase){
        Optional<CURDCase> caseOptional = curdTestRepository.findById(curdCase.getId());
        if (caseOptional.isPresent()){
            return curdTestRepository.save(curdCase);
        }else {
            CURDCase curdCase1 = new CURDCase();
            curdCase1.setCol("NoFindCase");
            return curdCase1;
        }
    }

    /**
     * 查询是否存在要删除的实例对象，有则删
     * @param curdCase 实例对象
     * @return String
     */
    public String delByID(CURDCase curdCase){
        Optional<CURDCase> caseOptional = curdTestRepository.findById(curdCase.getId());
        if (caseOptional.isPresent()){
            curdTestRepository.deleteById(curdCase.getId());
            return "success";
        }else {
            return "NoFindCase";
        }
    }
}
